package geom;


/**
 * This class models a rectangle
 * @author Magnus Brand
 *
 */
public class Rectangle extends Shape {
	
	private double width, height;
	/**
	 * position is the upper left corner.
	 */
	Point position;
	/**
	 * Creates a new rectangle.
	 * @param position The upper left corner
	 * @param width Width
	 * @param height Height
	 */
	public Rectangle(Point position, double width, double height) {
		if(width <0 || height <0 ) throw new IllegalArgumentException("Width and size must be >=0");
		this.width=width;
		this.height=height;
		this.position=position;
	}
	/**
	 * Computes the area
	 * @return Area of the shape
	 */
	@Override
	public double area() {
		return width*height;
	}
	/**
	 * Checks if a point lies in the shape.
	 * @return True if point in shape; false otherwise
	 */
	@Override
	public boolean pointInShape(Point point) {
		boolean xInShape=false;
		boolean yInShape=false;
		xInShape = ( (position.getX() <= point.getX()) && (point.getX() <= (position.getX() + width)) );
		yInShape = ( (position.getY() >= point.getY()) && (point.getY() >= (position.getY() - height)) );
		return xInShape && yInShape;
	}
	/**
	 * Checks if a point lies on the edge of the shape.
	 * @return True if point on edge; false otherwise.
	 */
	@Override
	public boolean pointOnEdge(Point point) {
		// A line is a rectangle with one dimension = 0.
		// Create 4 lines (rectangles) and check if pointInShape.
		Rectangle r1 = new Rectangle(position, width, 0),
				  r2 = new Rectangle(new Point(position.getX() + width, position.getY()), 0, height),
				  r3 = new Rectangle(new Point(position.getX(), position.getY() - height), width, 0),
				  r4 = new Rectangle(position, 0, height);
		for(Rectangle r : new Rectangle[] {r1,r2,r3,r4}) {
			if(r.pointInShape(point))
				return true;
		}
		// point was in neither r1-r4
		return false;
	}
	/**
	 * Returns the position of the shape
	 * @return The coordinates of the position
	 */
	@Override
	public Point getPosition() {
		return position;
	}

}
